package org.sczfdf.utils;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.date.SystemClock;
import org.sczfdf.bean.CmdInfo;
import org.sczfdf.conf.GitConf;
import org.sczfdf.exception.SyncException;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author Created by cgb
 * @date 2023/1/31
 */
public class GitUtil {
    private static final Integer SYNC_INTERVAL;
    private static volatile LocalDateTime lastSyncTime = LocalDateTimeUtil.of(0);
    private static final ScheduledExecutorService EXECUTOR = Executors.newScheduledThreadPool(1);
    private static final BlockingQueue<Runnable> QUEUE = ((ThreadPoolExecutor) EXECUTOR).getQueue();

    static {
        GitConf gitConf = GitConf.get();
        SYNC_INTERVAL = gitConf.getGitPushInterval();
    }

    private static boolean checkInterval() {
        LocalDateTime now = LocalDateTime.now();
        Duration between = LocalDateTimeUtil.between(lastSyncTime, now);

        boolean pass = between.getSeconds() > SYNC_INTERVAL;
        LogUtil.logInfo("git 上次同步时间[" + DateUtil.formatLocalDateTime(lastSyncTime) + "], " +
                (pass ? "满足间隔" : "不满足间隔") +
                "["+ SYNC_INTERVAL +"秒]");
        if (pass) {
            lastSyncTime = now;
        }
        return pass;
    }

    private static String cmd(String cmd, List<String> args) {
        List<String> cmdList = new ArrayList<>();
        cmdList.add("git");
        cmdList.add(cmd);
        cmdList.addAll(args);

        return CmdUtil.cmd(new CmdInfo()
                .setCmds(cmdList)
                .setDir(GitConf.get().getGitPath())
        );
    }

    private static void addAll() {
        cmd("add", ListUtil.of("."));
    }

    private static boolean checkUpdate() {
        String status = cmd("status", ListUtil.of("-s", "-uno"));

        return !status.isEmpty();
    }


    private static void commit() {
        cmd("commit", ListUtil.of("-m", SystemClock.nowDate()));
    }

    private static void push() {
        cmd("push", new ArrayList<>());
    }

    public static void pull() {
        if (!checkInterval()) {
            return;
        }

        try {
            cmd("pull", new ArrayList<>());
        } catch (SyncException e) {
            MailUtil.sendMail(e.getMessage());
        }
    }


    public static void pushAll() {
//        if (!checkInterval()) {
//            return;
//        }
        if (QUEUE.isEmpty()) {
            EXECUTOR.schedule(GitUtil::pushAll0, SYNC_INTERVAL, TimeUnit.SECONDS);
        }
    }

    private static void pushAll0() {
        try {
            if (checkUpdate()) {

                addAll();

                commit();

                push();

            }
        } catch (SyncException e) {
            MailUtil.sendMail(e.getMessage());
        }
    }
}
